// const { codegen } = require('@custom/swagger-axios-codegen')
// const { isEmpty } = require('lodash-es')
// const colors = require('colors')
// const prettier = require('prettier')
import { codegen } from 'swagger-axios-codegen'
import { isEmpty } from 'lodash-es'
import colors from 'colors'
import prettier from 'prettier'

/**
 * *用于配置多服务器来生成 api 接口文件;
 * url: swagger json 地址
 * name: 生成的文件名字
 */

const APIRemote = [
  {
    url: 'http://localhost:8081/v3/api-docs',
    name: 'BaseApi'
  }
]

/**
 * ! use custom format, fork from :
 * https://github.com/Manweill/swagger-axios-codegen
 * package is https://github.com/ysneo/swagger-axios-codegen.git
 */

// *每个文件处理好后，再处理下一个
async function makeFiles() {
  const promises = []
  for (const api of APIRemote) {
    const p = await generateAPI(api)
    promises.push(p)
  }

  await Promise.all(promises)
  console.log('\n---- Finished ! ! ! ----'.bgGreen.bold)
}

// *执行
makeFiles()

async function generateAPI(api) {
  if (isEmpty(api.url) || isEmpty(api.name)) {
    return
  }
  try {
    console.log(`\n---- Generate [${api.name}.ts] file ----`.cyan.bold)

    await codegen({
      serviceNameSuffix: '',
      useStaticMethod: true,
      methodNameMode: 'operationId',
      remoteUrl: api.url,
      openApi: '2',
      methodNameMode: 'path',
      outputDir: './src/service',
      fileName: api.name + '.ts',
      useClassTransformer: false,
      format: (s) => {
        const options = {
          printWidth: 100,
          tabWidth: 2,
          singleQuote: true,
          allowParens: true,
          trailingComma: 'es5',
          endOfLine: 'auto',
          // jsxBracketSameLine: true,
          arrowParens: 'avoid',
          parser: 'typescript'
        }

        // const hackString = s.replace(/Date;/g, 'string;').replace(/object;/g, 'any;');

        const result = prettier.format(s, options)

        return result
      }
    })

    console.log(`---- [${api.name}.ts] build successful ----\n`.green.bold)
  } catch (error) {
    console.log(`\n---- [${api.name}.ts] build error !!! ----\n`.red.bold)
    console.log(error)
  }
}
